package com.dy.cloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.cloud.mapper.PaymentMapper;
import com.dy.cloud.pojo.Entity.PaymentEntity;
import com.dy.cloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName:
 * @Author: 仄言in
 * @Desctiption: (描述)
 * @Date: 2021/9/2 17:17
 * @Version 1.0 (版本)
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, PaymentEntity> implements PaymentService {
    @Override
    public String payment_ok(Integer id) {
        return "当前线程池"+Thread.currentThread().getName()+"  payment_ok.id "+id+"  (σﾟ∀ﾟ)σ..:*☆哎哟不错哦";
    }

    /**
     *
     * HystrixCommand：服务降级的注解，表示这个方法出现问题，需要执行另一个方法，@HystrixProperty(name,value):表示这个线程池只能允许3s的请求时间，大于
     * 3s就会报错
     * @param id
     * @return
     **/
    @Override
    @HystrixCommand(fallbackMethod = "payment_timoutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String payment_timout(Integer id) {
        try {
            int timout=1;
            TimeUnit.SECONDS.sleep(timout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "当前线程池"+Thread.currentThread().getName()+"  payment_timeout.id "+id+"  ∑(っ°Д°;)っ卧槽，不见了";
    }

    @Override
    public String payment_timoutHandler(Integer id) {
        return "当前线程池"+Thread.currentThread().getName()+"  payment_timoutHandler.id "+id+" 8001系统繁忙，或者系统错误  Σσ(・Д・；)我我我什么都没做!!!";
    }
    /**
     * 熔断功能
     * @param id
     * @return
     **/
    @HystrixCommand(fallbackMethod="paymentCircuitBreaker_Fallback",commandProperties={
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),                       //--->是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),          //--->请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),    //--->时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),        //--->失败率达到多少后跳闸
    })
    @Override
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("---------id不能为空！");
        }
        String uuid = IdUtil.simpleUUID();
        return "当前线程："+Thread.currentThread().getName()+" 调用成功，流水号："+uuid;
    }
    public String paymentCircuitBreaker_Fallback(Integer id){
        return "id 不能为负，请稍后重试，(▼ヘ▼#) id"+id;
    }

}
